using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using TouchScript.InputSources;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;

public class RippleEffectManager : MonoBehaviour
{
    public static RippleEffectManager instance;
    public TuioInput tuioInput;
    public GameObject ripplePrefab; // 拖入 Image 的预设
    public GameObject canvas; // 拖入您的 Canvas 对象
    public float expansionSpeed = 1f; // 控制扩散速度
    public float maxRadius = 1f; // 最大扩散半径
    public float thickness = 0.05f; // 光圈厚度
    public float fadeWidth = 1f;
    public float falloff = 2f;
    public GameObject lightOn;
    private bool isLightOn = false;

    public AudioSource touchAudioSource;

    private bool isRippleEffectActive = true;

    // 用于跨线程传递任务到主线程
    private Queue<Action> mainThreadActions = new Queue<Action>();

    private void Start()
    {
        Screen.SetResolution(1165,211,true);
        
        instance = this;
        if (tuioInput == null)
        {
            tuioInput = FindObjectOfType<TuioInput>();
        }
        if (tuioInput != null)
        {
            tuioInput.OnCursorUpdateEvent += OnCursorUpdateEventCallBack;
        }
        else
        {   
            Debug.LogError("未找到 TuioInput 实例！");
        }
    }

    // 事件回调（可能不在主线程）
    private void OnCursorUpdateEventCallBack(Vector2 msg)
    {
        Debug.Log("订阅消息 : " + msg);
        if (isRippleEffectActive)
        {
            lock (mainThreadActions)
            {
                mainThreadActions.Enqueue(() => CreateRipple(msg));
            }
        }
    }

    void Update()
    {
        // 执行所有等待的主线程任务
        lock (mainThreadActions)
        {
            while (mainThreadActions.Count > 0)
            {
                mainThreadActions.Dequeue()?.Invoke();
            }
        }

        if (Input.GetMouseButtonDown(0))
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
            CreateRipple(Input.mousePosition);
        }
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            isLightOn = !isLightOn;
            if (isLightOn)
            {
                lightOn.SetActive(true);
            }
            else
            {
                lightOn.SetActive(false);
            }
        }
    }

    public void CreateRipple(Vector2 position)
    {
        Debug.Log("创建光圈");
        if (!isRippleEffectActive)
        {
            return;
        }
        // isRippleEffectActive = false;
        StartCoroutine(ToggleInteractionCoroutine(position));
        touchAudioSource.Play();
        GameObject newRipple = Instantiate(ripplePrefab, canvas.transform);
        newRipple.transform.localPosition = position - new Vector2(Screen.width / 2, Screen.height / 2);

        Material rippleMaterial = new Material(newRipple.GetComponent<Image>().material);
        rippleMaterial.SetVector("_Center", new Vector2(0.5f, 0.5f));
        rippleMaterial.SetFloat("_Thickness", GlobalData.Thickness);
        rippleMaterial.SetFloat("_FadeWidth",GlobalData.FadeWidth);
        rippleMaterial.SetFloat("_Falloff",GlobalData.Falloff);

        Color color = rippleMaterial.GetColor("_Color");
        color.a = 0f;
        rippleMaterial.SetColor("_Color", color);
        DOTween.To(() => color.a, x => { color.a = x; rippleMaterial.SetColor("_Color", color); }, 1f, 2f);

        newRipple.GetComponent<Image>().material = rippleMaterial;
        StartCoroutine(ExpandRipple(newRipple, rippleMaterial));
    }

    IEnumerator ExpandRipple(GameObject ripple, Material rippleMaterial)
    {
        float currentRadius = 0.0f;
        while (currentRadius < GlobalData.MaxRadius)
        {
            currentRadius += Time.deltaTime * GlobalData.ExpansionSpeed;
            rippleMaterial.SetFloat("_Radius", currentRadius);
            yield return null;
        }
        Destroy(ripple);
        // isRippleEffectActive = true;
    }

    IEnumerator ToggleInteractionCoroutine(Vector2 position)
    {
        isRippleEffectActive = false; 
        float x = position.x - 582.5f;
        x = math.abs(x);
        float time =  6 + x * 4 / 582.5f;
        yield return new WaitForSeconds(time);
        isRippleEffectActive = true;
    }
}
